<template>
	<cu-custom :isBack="true">
		<template #title>最近消息</template>
	</cu-custom>
	
	<view class="page-content">
		<view class="mb-3" v-for="(item, index) in dataList" :key="index">
			<MessageBox
				:id="item.id"
				:title="item.title"
				v-model:status="item.status"
				:generate-status="item.generateStatus"
				:content="item.content"
				:date="item.date"
				:type="item.type"
				:relation-id="item.relationId"
			/>
		</view>
		<view class="cu-load text-gray" :class="status === 'loading' ? 'loading' : 'over'"></view>
	</view>
</template>

<script setup lang="ts">
import { onLoad, onReachBottom } from "@dcloudio/uni-app"
import { getMessage } from "@/api/user.js"
import MessageBox from "./components/MessageBox.vue"
import { ref, type Ref } from "vue"

interface IMessage {
	id: number
	title: string
	type: string
	status: string
	content: string
	date: string,
	relationId?: number
	generateStatus: string
}

const mockData:Ref<IMessage[]> = ref([
	{
		title: "生成报告",
		type: "report",
		status: "unread",
		content: "宁波市实验中学20230123报告生成中",
		date: "11月04日"
	},
	{
		title: "生成报告",
		type: "report",
		status: "success",
		content: "宁波市实验中学20230123报告生成完成",
		date: "11月05日"
	},
	{
		title: "任务一览",
		type: "mission",
		status: "warning",
		content: "宁波市实验学校发生食物中毒事件",
		date: "11月05日"
	}
] as IMessage[])

const statusMap = {
	"1": "unread",
	"2": "read"
}
const typeMap = {
	"1": "mission",
	"2": "report",
	"3": "notice",
	"4": "statistics",
	"5": "rectification"
}

const status:Ref<string> = ref("loadmore")
let currPage:number = 1
const dataList:Ref<any[]> = ref([])
const loadData = (type = "default"):void => {
	if (type === "refresh") {
		currPage = 1
		status.value = "loadmore"
		dataList.value = []
	}
	if (status.value === 'loading' || status.value === 'over') return
	status.value = "loading"
	getMessage({
		pageNum: currPage++,
		pageSize: 10,
	}).then((res:any) => {
		const rows = res.rows
		
		let data:IMessage[] = []
		for (let v of rows) {
			console.log(v.createTime)
			data.push({
				id: v.id,
				title: v.msgTitle,
				content: v.msgContent,
				type: typeMap[v.type],
				status: statusMap[v.status],
				generateStatus: v.generateStatus,
				// date: String((new Date(v.createTime)).getTime()),
				date: v.createTime ? v.createTime.match(/-(.*) /)[1] : "",
				relationId: v.resourcesId
			})
		}
		dataList.value.push(...data)
		status.value = rows.length < 10 ? "over" : "loadmore"
		if (type === "refresh") uni.stopPullDownRefresh()
	})
}
onReachBottom(() => {
	loadData() 
})
onLoad((options:any):void => {
	loadData("refresh")
})

</script>

<style lang="stylus" scoped></style>